package com.topteam.frame.controllor;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.jfinal.plugin.activerecord.Page;
import com.topteam.component.easyui.EasyTreeModel;
import com.topteam.component.easyui.EasyTreeNode;
import com.topteam.component.easyui.Paginate;
import com.topteam.core.Path;
import com.topteam.frame.entity.FrameDept;
import com.topteam.frame.entity.FrameUser;
import com.topteam.frame.entity.FrameUserExt;
import com.topteam.frame.vo.FrameUserVO;
import com.topteam.utility.CommUtil;
import com.topteam.utility.StringUtil;
import com.topteam.utility.VOUtil;


@Path("/frameuser")
public class FrameUserController extends BaseController {

	public void list() {
		render("/frame/FrameUserList.html");
	}

	public void changepass() {
		render("/frame/FrameUserChangePassPage.html");
	}

	public void changepassword() {

	}

	public void index() {
		List<FrameUser> list = FrameUser.dao.getAllUsers();
		renderJson(list);
	}

	public void save() {
		FrameUser u = getModel(FrameUser.class, "user");
		String userId = UUID.randomUUID().toString();
		u.set("id", userId);
		u.set("password", CommUtil.md5("11111"));
		u.save();
		FrameUserExt.dao.initUserExt(userId);
		renderText("保存成功", "text/html");
	}

	public void edit() {

		// Menu m = Menu.dao.findById(getPara());
		// setAttr("menu", m);

		setAttr("user", FrameUser.dao.findById(getPara()));

		renderFreeMarker("/frame/FrameUserEditPage.html");
	}

	public void update() {
		FrameUser u = getModel(FrameUser.class, "user");
		// m.set("deptcode", User.dao.getNextCode(u.getStr("parentId")));
		u.update();
		renderText("修改成功", "text/html");
	}

	public void add() {
		setAttr("parentId", getPara("parentId"));
		setAttr("user", new FrameUser());
		renderFreeMarker("/frame/FrameUserAddPage.html");
	}

	public void delete() {
		String ids = getPara("ids");
		FrameUser.dao.deleteIds(ids);
		renderText("删除成功", "text/html");
	}

	public void resetpass() {
		String ids = getPara("ids");
		boolean success = true;
		try {
			FrameUser.dao.resetPass(ids);
		} catch (SQLException e) {
			success = false;
		}
		if (success) {
			renderText("密码已重置", "text/html");
		} else {
			renderText("密码重置失败", "text/html");
		}
	}

	public void table() {
		String username = getPara("username");
		String displayname = getPara("displayname");
		String deptcode = getPara("code");
		int page = getParaToInt("page");
		int size = getParaToInt("rows");
		Page<FrameUser> p = null;
		if (StringUtil.isNull(deptcode)) {
			p = FrameUser.dao.getUserPageBySearch(username, displayname, page,
					size);
		} else {
			p = FrameUser.dao.getUsersBySearchWithDept(deptcode, username,
					displayname, page, size);
		}

		Paginate paginate = Paginate.build(p);
		renderJson(paginate);
	}

	public void extable() {
		String userid = getPara("userid");

		FrameUser u;
		FrameDept d = new FrameDept();

		if (StringUtil.isNull(userid)) {
			u = FrameUser.dao.findFirst("select t.* from FrameUser t");
		} else {
			u = FrameUser.dao.findById(userid);
		}

		FrameUserVO o = new FrameUserVO(u, d);

		Paginate paginate = Paginate.build(VOUtil.porperty2MapList(o));
		renderJson(paginate);
	}

	
	/**
	 * 部门人员树
	 */
	public void deptUserTree(){
		EasyTreeModel model = new EasyTreeModel(this) {
			@Override
			public List fechDate(String id) {
				List list = new ArrayList();
				//先根据部门ID 查人
				String userSql = "select u.*, 0 as has  from FrameDept d RIGHT join UserDeptRelation ud on d.id=ud.deptId RIGHT join FrameUser u on ud.userId = u.id where d.id=? order by u.order desc";
				List<FrameUser> userList  = FrameUser.dao.find(userSql, id);
				//再查部门
				List<FrameDept> deptList = new ArrayList<FrameDept>();
				if(id == null){
					String sql = "select t.*, case when (SELECT count(1) from FrameDept t2 where t2.parentId=t.id)>0 then 1 ELSE 0 END as has,case when (SELECT count(1) from UserDeptRelation ud where ud.deptId=t.id)>0 then 1 ELSE 0 END as hasU   from FrameDept t where t.parentId is null order by t.order desc";
					deptList = FrameDept.dao.find(sql);
				}
				else{
					String sql = "select t.*, case when (SELECT count(1) from FrameDept t2 where t2.parentId=t.id)>0 then 1 ELSE 0 END as has ,case when (SELECT count(1) from UserDeptRelation ud where ud.deptId=t.id)>0 then 1 ELSE 0 END as hasU from FrameDept t where t.parentId=? order by t.order desc";
					deptList = FrameDept.dao.find(sql,id);
				}
				list.addAll(userList);
				list.addAll(deptList);
				return list;
			}

			@Override
			public EasyTreeNode model2Node(Object t) {
				EasyTreeNode node = new EasyTreeNode();
				if(t instanceof FrameUser){
					FrameUser u = (FrameUser) t;
					node.setId(u.getStr("id"));
					node.setText(u.getStr("username"));
					node.setIconCls("icon-online");
					Map<String, String> map = new HashMap<String, String>();
					map.put("type", "User");
					node.setAttributes(map);
					boolean hasChild = u.getLong("has")>0L;
					node.setHasChild(hasChild);
				}else if(t instanceof FrameDept){
					FrameDept d = (FrameDept) t;
					node.setId(d.getStr("id"));
					node.setText(d.getStr("deptName"));
					Map<String, String> map = new HashMap<String, String>();
					map.put("type", "Dept");
					node.setAttributes(map);
					boolean hasChild = d.getLong("has")>0L||d.getLong("hasU")>0L;
					node.setHasChild(hasChild);
				}
				return node;
			}
		};
		
		renderJson(model.toJson());
	}

}
